﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Objects;
using AjaxControlToolkit;

namespace Client_Revenue
{
    public partial class AddContract : System.Web.UI.Page
    {

        #region "Properties & Fields"
        public string FullName = string.Empty;
        private ContractLineOfBusiness _contractLofBiz = new ContractLineOfBusiness();
        private SalesInfo _SalesInfo = new SalesInfo();

        private List<SalesInfo> iSalesInfo
        {
            get
            {
                if (this.ViewState["iSalesInfo"] == null)
                    return null;

                return (List<SalesInfo>)this.ViewState["iSalesInfo"];
            }
            set { this.ViewState["iSalesInfo"] = value; }
        }
        private List<ContractLineOfBusiness> iContractLinesOfBiz
        {
            get
            {
                if (this.ViewState["iContractLinesOfBiz"] == null)
                    return null;

                return (List<ContractLineOfBusiness>)this.ViewState["iContractLinesOfBiz"];
            }
            set { this.ViewState["iContractLinesOfBiz"] = value; }
        }
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {

                LoadPageData();
            }
        }

        public void LoadPageData()
        {
            iContractLinesOfBiz = new List<ContractLineOfBusiness>();
            iSalesInfo = new List<SalesInfo>();

            using (var DE = new dominiumEntities())
            {
                //clients
                var theClients = (from c in DE.Clients
                                  join t in DE.ClientTypes on c.ClientTypeId equals t.ClientTypeId
                                  orderby c.ClientName ascending
                                  select new { c.ClientId, c.ClientName, t.ClientTypeName }
                                 ).Distinct().ToList();

                ddClient.DataSource = theClients;
                ddClient.DataTextField = "ClientName";
                ddClient.DataValueField = "ClientId";
                ddClient.DataBind();

                //Business Lines
                var lob = (from l in DE.LineOfBusinesses select new { l.LineOfBusinessId, l.LoBName }).Distinct().ToList();

                chlLineOfBiz.DataSource = lob;
                chlLineOfBiz.DataTextField = "LoBName";
                chlLineOfBiz.DataValueField = "LineOfBusinessId";
                //chlLineOfBiz.SelectedIndex = 0;
                chlLineOfBiz.DataBind();


                //Carriers
                var carriers = (from c in DE.Carriers select new { c.CarrierId, c.CarrierName }).Distinct().ToList();

                ddCarrier.DataSource = carriers;
                ddCarrier.DataTextField = "CarrierName";
                ddCarrier.DataValueField = "CarrierId";
                ddCarrier.DataBind();

                //Insurance Types
                var instype = (from i in DE.InsuranceTypes select new { i.InsuranceTypeId, i.InsuranceTypeName }).Distinct().ToList();

                ddInsuType.DataSource = instype;
                ddInsuType.DataTextField = "InsuranceTypeName";
                ddInsuType.DataValueField = "InsuranceTypeId";
                ddInsuType.SelectedIndex = 0;
                ddInsuType.DataBind();

            }
            txtStartDate.Text = DateTime.Today.ToShortDateString();
        }


        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                //Add Contract
                using (var DE = new dominiumEntities())
                {
                    ObjectParameter sContractId = new ObjectParameter("ContractId", typeof(int));

                    //AddContract
                    DE.AddContract(int.Parse(ddClient.SelectedValue), DateTime.Parse(txtStartDate.Text), txtContractNotes.Text, ddClient.SelectedItem.Text, sContractId);

                    //AddEstimates
                    DE.AddContractEstimates(Convert.ToInt32(sContractId.Value), Convert.ToDecimal(txtEstimatedRev.Text), Convert.ToInt32(txtHeadCount.Text), txtContractNotes.Text);

                    //Add Contract Lines of Business
                    foreach (ContractLineOfBusiness theBiz in iContractLinesOfBiz)
                    {
                        DE.AddContractsLinesOB(theBiz.LineOfBusinessId,Convert.ToInt32(sContractId.Value), theBiz.CarrierId, theBiz.InsuranceTypeId, theBiz.Commission);
                    }
                }
            }
            catch (Exception ex)
            { throw ex; }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            //SSE659-PR3-A4
            ResetFormControlValues(this);
        }
        
        private void ResetFormControlValues(Control parent)
        {
            foreach (Control c in parent.Controls)
            {
                if (c.Controls.Count > 0)
                {
                    ResetFormControlValues(c);
                }
                else
                {
                    switch (c.GetType().ToString())
                    {
                        case "System.Web.UI.WebControls.TextBox":
                            //SSE659-PR3-A4
                            ((TextBox)c).Text = "";
                            txtHeadCount.Text = "0";
                            txtEstimatedRev.Text = "0.00";
                            txtStartDate.Text = DateTime.Today.ToShortDateString();
                            break;
                        case "System.Web.UI.WebControls.CheckBox":
                            if (((CheckBox)c).Checked == false)
                            { ((CheckBox)c).Checked = true; }
                            else
                            {
                                ((CheckBox)c).Checked = false;
                            }
                            using (var DE = new dominiumEntities())
                            {
                                //SSE659-PR3-A4
                                var lob = (from l in DE.LineOfBusinesses select new { l.LineOfBusinessId, l.LoBName }).Distinct().ToList();
                                chlLineOfBiz.DataSource = lob;
                                chlLineOfBiz.DataTextField = "LoBName";
                                chlLineOfBiz.DataValueField = "LineOfBusinessId";
                                chlLineOfBiz.DataBind();
                            }
                            break;
                        case "System.Web.UI.WebControls.RadioButton":
                            ((RadioButton)c).Checked = false;
                            break;
                    }
                }
            }
        }

        protected void chlLineOfBiz_SelectedIndexChanged(object sender, EventArgs e)
        {
            //SSE659-PR3-A1
            pnlPopup.Visible = true;
        }

        protected override void Render(System.Web.UI.HtmlTextWriter writer)
        {
            ClientScript.RegisterForEventValidation("ddProducerRole ", "PersonId");
            ClientScript.RegisterForEventValidation("ddCarrier ", "CarrierId");
            ClientScript.RegisterForEventValidation("ddInsuType ", "InsuranceTypeID");

            base.Render(writer);
        }


        protected void BtnSubmit_Click(object sender, EventArgs e)
        {
            int carrierId = Convert.ToInt32(ddCarrier.SelectedValue);
            int instypeId = Convert.ToInt32(ddInsuType.SelectedValue);
            string LoBComm = txtLoBComm.Text;
            var selectedLoB = (from ListItem i in chlLineOfBiz.Items where i.Selected select i);
            if (selectedLoB.LastOrDefault().Value != null)
            {
                HiddenFieldLoB.Value = selectedLoB.LastOrDefault().Value;
            }
            else
            {
                HiddenFieldLoB.Value = "1000";  //Medical
            };

            //get values 
            _contractLofBiz.Commission = Decimal.Parse(LoBComm);
            _contractLofBiz.InsuranceTypeId = instypeId;
            _contractLofBiz.CarrierId = carrierId;
            _contractLofBiz.LineOfBusinessId = Convert.ToInt32(HiddenFieldLoB.Value);

            ////add the line item to the list
            iContractLinesOfBiz.Add(_contractLofBiz);

            //SSE659-PR3-A1
            pnlPopup.Visible = false;
        }

        
        protected void ddClient_SelectedIndexChanged(object sender, EventArgs e)
        {
            //SSE659-PR3-A3
            ResetFormControlValues(this);

            using (var DE = new dominiumEntities())
            {
                //SSE659-PR3-A2
                var theContracts = (from c in DE.Clients
                                    join co in DE.Contracts on c.ClientId equals co.ClientId
                                    join ce in DE.ContractEstimates on co.ContractId equals ce.ContractId                                 
                                    select new
                                    {
                                        c.ClientId,
                                        c.ClientName,
                                        ce.HeadCount,                                       
                                        ce.EstimatedRevenue,
                                        co.StartDate,
                                        co.ContractNotes
                                    }).ToList();

                for (int i = 0; i < theContracts.Count; i++ )
                {
                    if (ddClient.SelectedItem.Text == theContracts[i].ClientName)
                    {
                        var lob = (from l in DE.ContractLineOfBusinesses select new
                        { l.LineOfBusinessId, l.CarrierId, l.InsuranceTypeId, l.Commission }).ToList();

                        for (int n = 0; n < lob.Count; n++)
                        {
                            chlLineOfBiz.SelectedIndex = lob[n].LineOfBusinessId - 1000;
                            ddCarrier.SelectedIndex = lob[n].CarrierId - 1000;
                            ddInsuType.SelectedIndex = lob[n].InsuranceTypeId - 1000;
                            txtLoBComm.Text = lob[n].Commission.ToString();
                        }
                        txtStartDate.Text = theContracts[i].StartDate.ToString();
                        txtHeadCount.Text = theContracts[i].HeadCount.ToString();
                        txtEstimatedRev.Text = theContracts[i].EstimatedRevenue.ToString();
                        txtContractNotes.Text = theContracts[i].ContractNotes.ToString();
                    }
                }
            }
        }
    }
}